import { bufferToString } from "../util.js";

export class CheckData {
    // /** 原始数据 */
    // readonly #buf: Uint8Array;

    /** 待比较的数据 */
    #data: Uint8Array;

    constructor(buf: Uint8Array) {
        // this.#buf = buf;
        this.#data = buf.subarray(0, buf.length);
    }

    consume(length: number): Uint8Array {
        if (length > this.#data.length) throw new Error("数据长度不足");
        const data = this.#data.subarray(0, length);
        this.#data = this.#data.subarray(length, this.#data.length);
        return data;
    }

    hasPrefix(prefix: ArrayLike<number>): boolean {
        if (this.#data.length < prefix.length) return false;
        for (let i = 0; i < prefix.length; i++) {
            if (this.#data[i] !== prefix[i]) return false;
        }
        return true;
    }

    get length(): number {
        return this.#data.length;
    }

    /**
     * 读取指定位置的字节
     * @param index 起始位置
     * @returns 字节值
     */
    u8(index: number = 0): number {
        if (index < 0 || index >= this.#data.length) throw new Error("数据越界");
        return this.#data[index]!;
    }

    /**
     * 读取16位的无符号整数
     * @param index 起始位置
     * @returns
     */
    u16le(index: number = 0): number {
        if (index < 0 || index + 2 > this.#data.length) throw new Error("数据越界");
        return this.#data[index]! | (this.#data[index + 1]! << 8);
    }

    /**
     * 读取32位的无符号整数
     * @param index 起始位置
     * @returns
     */
    u32le(index: number = 0): number {
        if (index < 0 || index + 4 > this.#data.length) throw new Error("数据越界");
        return (
            this.#data[index]! |
            (this.#data[index + 1]! << 8) |
            (this.#data[index + 2]! << 16) |
            (this.#data[index + 3]! << 24)
        );
    }

    /**
     * 读取指定长度的十六进制数据
     * @param len 需要读取的长度
     * @returns 十六进制字符串
     */
    hex(len: number): string {
        if (len === 0) return "";
        if (len > this.#data.length) throw new Error("数据长度不足");
        let buf = this.#data.subarray(0, len);
        return bufferToString(buf);
    }

    /**
     * 读取指定长度的字符串数据
     * @param len 需要读取的长度
     * @returns 字符串
     */
    string(len: number): string {
        if (len === 0) return "";
        if (len > this.#data.length) throw new Error("数据长度不足");
        const data = this.#data.subarray(0, len);
        const decoder = new TextDecoder("utf-8");
        return decoder.decode(data);
    }
}
